import { fetchList } from '@/api/api'

export default async function getRouter() {
  // if (
  //   localStorage.getItem('角色编号') ||
  //   localStorage.getItem('角色编号') === '' ||
  //   localStorage.getItem('角色编号') === undefined
  // ) {
  //   const param = { query: 'vue_角色list', username: localStorage.ghusername }
  //   fetchList(param).then(({ data }) => {
  //     console.info(data)
  //     localStorage.角色编号 = data.data[0].角色编号
  //   })
  // }
  const param = {
    query: 'vue_获取动态路由',
    角色编号: localStorage.getItem('角色编号')
  }
  // if(!store.state.permission.routers||store.state.permission.routers.length===0){
  var ss = await fetchList(param).then(({ data }) => {
    if (data.flag === '1' && data.data && data.data.length > 0) {
      const sorted = toTree(data.data)
      const accessedRouters = formatRoutes(sorted)
      accessedRouters.forEach(item => {
        if (item['children']) {
          item['redirect'] = item.children[0].path
        }
      })
      return accessedRouters
    } else {
      return []
    }
  })
  return ss
}

function toTree(array) {
  array.forEach(item => {
    if (item.childrens) delete item.childrens
  })
  const map = {}
  array.forEach(item => {
    map[item.sysid] = item
  })
  const val = []
  array.forEach(item => {
    const parent = map[item.Pid]
    // 好绕啊，如果找到索引，那么说明此项不在顶级当中,那么需要把此项添加到，他对应的父级中
    if (parent) {
      (parent.childrens || (parent.childrens = [])).push(item)
    } else {
      // 如果没有在map中找到对应的索引ID,那么直接把 当前的item添加到 val结果集中，作为顶级
      val.push(item)
    }
  })
  return val
}
function formatRoutes(aMenu) {
  const aRouter = []
  aMenu.forEach(obj => {
    const oRouter = {
      path: obj.Path,
      component(resolve) {
        let componentPath = ''
        if (obj.Component === 'Layout') {
          require(['@/views/layout/Layout'], resolve)
          return
        } else {
          componentPath = obj.Component
        }
        require([`@/views${componentPath}.vue`], resolve)
        // resolve => require.ensure([], () => resolve(require('../views' + componentPath + '.vue')));
      },
      meta: {
        title: obj.Title && obj.Title !== '' ? obj.Title : obj.名称,
        icon: obj.Icon
      },
      name: obj.名称,
      icon: obj.Icon
    }

    console.info(obj.Title)
    if (obj.状态 === '1' || parseInt(obj.状态) === 1) {
      oRouter['hidden'] = 'true'
    }
    if (obj.childrens) {
      oRouter['children'] = formatRoutes(obj.childrens)
    }
    aRouter.push(oRouter)
  })
  return aRouter
}
